<template>
  <m-modal ref="modalRef" title="设置权限" @ok="handleOk">
    <a-form>
      <a-form-item label="切换应用">
        <a-select @change="requestData" v-model:value="currentAppId" placeholder="请选择应用名称">
          <a-select-option v-for="item in appData" :key="item.value" :value="item.value">
            {{item.label}}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <a-tree
    @check="handleCheck"
    v-model:checkedKeys="checkedKeys"
    :tree-data="treeData" :fieldNames="{
      title: 'name',
      key: 'id',
      value: 'id',
      children: 'children'
    }" checkable></a-tree>
  </m-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { menuList, appList, roleMenuList, saveRoleMenu } from '/@/api/sys/role'
import { TreeNode } from '/@/utils/tree';
const modalRef = ref()
const currentRecord = ref();
const currentAppId = ref()
const treeData = ref<Array<any>>([])
const appData = ref<Array<any>>([])
const checkedKeys = ref<Array<any>>([])
const submitCheckedKeys = ref<Array<any>>([])
const leafKeys = ref<Array<any>>([])
const requestData = () =>{
    menuList({
      m_EQ_appCode: currentAppId.value
    }).then(data=>{
      leafKeys.value = []
      treeData.value = new TreeNode({
        rowHandle:(item: any)=>{
          if(!item.children) {
            leafKeys.value.push(item.id)
          }
        }
      }).build(data.data, '0')
      roleMenuList({
        appCode: currentAppId.value,
        roleId: currentRecord.value.id
      }).then(data=>{
        submitCheckedKeys.value = data.data || []
        // 勾选值必须为叶子节点
        checkedKeys.value = submitCheckedKeys.value.filter(item=>{
          return leafKeys.value.includes(item)
        })
      })
    })
}
const handleCheck = (checkedKeys: any, e: any) =>{
  // 提交必须包含父节点，即半选值也要提交
  submitCheckedKeys.value = [...checkedKeys, ...e.halfCheckedKeys];
}
const handleOk = () => {
  const params = submitCheckedKeys.value.map((menuId: any)=>{
    return {
      roleId: currentRecord.value.id,
      menuId: menuId
    }
  })
  saveRoleMenu(params).then(()=>{
    modalRef.value.closeModal()
  })
}
defineExpose({
  show(record: any) {
    if(!appData.value.length) {
      appList({}).then(data=>{
        appData.value = data.data || []
        currentAppId.value = appData.value[0].value
        requestData()
      })
    } else {
      currentAppId.value = appData.value[0].value
      requestData()
    }
    currentRecord.value = record;
    modalRef.value.openModal()
  }
})
</script>
<style lang="less" scoped>

</style>